package com.zzl.study.nacos.loadbalancer;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.zzl.study.nacos.properties.NacosMultiDiscoveryProperties;
import com.zzl.study.nacos.utils.InetIPv6Utils;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Nacos负载均衡器
 *
 * @author: zhangzl
 * @date: 2025/7/16 16:26
 * @version: 1.0
 */
@Slf4j
public class NacosLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    /**
     * 服务名称
     */
    private final String serviceId;

    /**
     * 服务提供者列表提供者
     */
    private final ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    /**
     * Nacos多注册中心属性配置
     */
    private final NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties;

    /**
     * IPv4正则表达式
     */
    private static final String IPV4_REGEX = "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}";

    /**
     * IPv6元数据Key
     */
    private static final String IPV6_KEY = "IPv6";

    /**
     * IPv6地址
     */
    public static String ipv6;

    /**
     * IPv6工具类
     */
    @Autowired
    private InetIPv6Utils inetIPv6Utils;

    /**
     * 构造方法
     *
     * @param serviceInstanceListSupplierProvider 服务实例列表提供者
     * @param serviceId                           服务名称
     * @param nacosMultiDiscoveryProperties       Nacos多注册中心属性配置
     */
    public NacosLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties) {
        this.serviceId = serviceId;
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.nacosMultiDiscoveryProperties = nacosMultiDiscoveryProperties;
    }

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        String ip = this.nacosMultiDiscoveryProperties.getIp();
        if (StringUtils.isNotEmpty(ip)) {
            ipv6 = Pattern.matches(IPV4_REGEX, ip) ? this.nacosMultiDiscoveryProperties.getMetadata().get(IPV6_KEY) : ip;
        } else {
            ipv6 = this.inetIPv6Utils.findIPv6Address();
        }
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);
        return supplier.get(request).next().map(this::getInstanceResponse);
    }

    /**
     * 获取服务实例
     *
     * @param serviceInstances 服务实例列表
     * @return 服务实例
     */
    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) {
        if (serviceInstances.isEmpty()) {
            log.warn("No servers available for service: " + this.serviceId);
            return new EmptyResponse();
        }
        try {
            String clusterName = this.nacosMultiDiscoveryProperties.getClusterName();
            List<ServiceInstance> instancesToChoose = serviceInstances;
            if (StringUtils.isNotBlank(clusterName)) {
                List<ServiceInstance> sameClusterInstances = serviceInstances.stream()
                        .filter(serviceInstance -> {
                            String cluster = serviceInstance.getMetadata().get("nacos.cluster");
                            return StringUtils.equals(cluster, clusterName);
                        }).toList();
                if (!CollectionUtils.isEmpty(sameClusterInstances)) {
                    instancesToChoose = sameClusterInstances;
                }
            } else {
                log.warn("A cross-cluster call occurs，name = {}, clusterName = {}, instance = {}", serviceId, clusterName, serviceInstances);
            }
            instancesToChoose = this.filterInstanceByIpType(instancesToChoose);
            ServiceInstance instance = NacosBalancer.getHostByRandomWeight3(instancesToChoose);
            return new DefaultResponse(instance);
        } catch (Exception e) {
            log.warn("NacosLoadBalancer error", e);
            return null;
        }
    }

    /**
     * 根据ip类型进行过滤
     *
     * @param instances 实例列表
     * @return 过滤后的实例列表
     */
    private List<ServiceInstance> filterInstanceByIpType(List<ServiceInstance> instances) {
        if (StringUtils.isNotEmpty(ipv6)) {
            List<ServiceInstance> ipv6InstanceList = new ArrayList<>();
            for (ServiceInstance instance : instances) {
                if (Pattern.matches(IPV4_REGEX, instance.getHost())) {
                    if (StringUtils.isNotEmpty(instance.getMetadata().get(IPV6_KEY))) {
                        ipv6InstanceList.add(instance);
                    }
                } else {
                    ipv6InstanceList.add(instance);
                }
            }
            if (ipv6InstanceList.isEmpty()) {
                return instances.stream().filter(instance -> Pattern.matches(IPV4_REGEX, instance.getHost())).toList();
            } else {
                return ipv6InstanceList;
            }
        }
        return instances.stream().filter(instance -> Pattern.matches(IPV4_REGEX, instance.getHost())).toList();
    }

}
